package com.vip.oauth2.controller;

import com.vip.common.constant.UrlConsts;
import com.vip.common.response.RestResponse;
import com.vip.common.response.RestResponses;
import com.vip.common.util.TokenUtils;
import com.vip.oauth2.service.ISysUserService;
import com.vip.oauth2resource.util.CustomUserDetail;
import com.vip.oauth2resource.util.UserHelper;
import com.vip.redis.component.RedisOperate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户授权管理
 *
 * @author wgb
 * @date 2020/3/20 15:56
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping(UrlConsts.AUTH + "/user")
public class SysUserController {

    private final ISysUserService userService;
    private final RedisTokenStore redisTokenStore;
    private final RedisOperate redisOperate;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping(value = "/login")
    public RestResponse<CustomUserDetail> userLogin(@RequestParam String username, @RequestParam String password) {
        return RestResponses.newResponseFromResult(userService.userLogin(username, password));
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    @GetMapping(value = "/curr")
    public RestResponse<CustomUserDetail> getCurrUser() {
        return RestResponses.newSuccessResponse(UserHelper.getUser());
    }


    /**
     * 用户注销
     *
     * @param authorization
     * @return
     */
    @GetMapping("/logout")
    public RestResponse logout(@RequestHeader("Authorization") String authorization) {
        String token = TokenUtils.extracteToken(authorization);
        redisTokenStore.removeAccessToken(token);
        redisTokenStore.removeRefreshToken(token);
        redisOperate.deleteCache(token);
        return RestResponses.newSuccessResponse("注销成功");
    }

}
